package com.tony.server.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tony.easymvc.core.TableUtils;
import com.tony.easymvc.mapper.DbInfoMapper;
import com.tony.easymvc.mapper.HtmlOperationMapper;
import com.tony.easymvc.mapper.ProjectInfoMapper;
import com.tony.easymvc.mapper.ProjectTablesMapper;
import com.tony.easymvc.po.DbInfo;
import com.tony.easymvc.po.HtmlOperation;
import com.tony.easymvc.po.HtmlOperationExample;
import com.tony.easymvc.po.ProjectBiz;
import com.tony.easymvc.po.ProjectInfo;
import com.tony.easymvc.po.ProjectTables;
import com.tony.server.JDBC;
import com.tony.server.service.HtmlProjectService;
import com.tony.server.service.ProjectBizService;

@Service("htmlProjectService")
public class HtmlProjectServiceImpl implements HtmlProjectService {

	@Resource
	HtmlOperationMapper htmlOperationMapper;
	@Resource
	ProjectInfoMapper projectInfoMapper;
	@Resource
	DbInfoMapper dbInfoMapper;

	@Resource
	ProjectTablesMapper projectTablesMapper;
	@Resource
	ProjectBizService projectBizServiceImpl;

	@Override
	public List<HtmlOperation> getHtmlOperation(int bizId, String tableName) {
		ProjectBiz projectBiz = projectBizServiceImpl.selectProjectBizFillDb(bizId);

		List<HtmlOperation> returnList = getHtmlOperation(projectBiz, tableName);

		if (returnList != null && !returnList.isEmpty()) {
			return returnList;
		}
		returnList = Lists.newArrayList();

		ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(projectBiz.getProjectId());
		if (projectInfo == null || projectBiz.getMaster() == null) {
			return returnList;
		}
		DbInfo dbinfo = projectBiz.getMaster();
		JDBC jdbc = new JDBC(projectInfo.getDriverClassName(), dbinfo.getJdbcUrl(), dbinfo.getUsername(),
				dbinfo.getPassword());
		String dbName = TableUtils.resoleSchema(dbinfo.getJdbcUrl());
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "select a.COLUMN_NAME, a.COLUMN_COMMENT,a.COLUMN_KEY  from Information_schema.columns as a  where  a.table_Name = '"
				+ tableName + "' and a.table_schema='" + dbName + "'";
		try {
			conn = jdbc.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			HtmlOperation ho = new HtmlOperation();
			try {
				while (rs.next()) {
					ho = new HtmlOperation();
					String columnName = rs.getString(1);
					String columnComment = rs.getString(2);
					String columnKey = rs.getString(3);
					ho.setColumnName(columnName);
					ho.setTitleName(columnComment);
					ho.setIsPrimary(StringUtils.equalsIgnoreCase(columnKey, "PRI") + "");
					returnList.add(ho);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(stmt);
			JdbcUtils.closeConnection(conn);
		}
		return returnList;
	}

	private List<HtmlOperation> getHtmlOperation(ProjectBiz projectBiz, String tableName) {
		List<HtmlOperation> resultHtmlOperationList = null;
		List<HtmlOperation> returnHtmlOperationList = null;
		if (projectBiz == null) {
			return Lists.newArrayList();
		}
		List<ProjectTables> projectTables = projectBiz.getProjectTables();
		if (CollectionUtils.isEmpty(projectTables)) {
			return Lists.newArrayList();
		}
		returnHtmlOperationList = new ArrayList<HtmlOperation>();
		for (int i = 0; i < projectTables.size(); i++) {
			ProjectTables projectTable = projectTables.get(i);
			if (StringUtils.equals(projectTable.getTableName(), tableName)) {
				if (CollectionUtils.isEmpty(projectTable.getHtmlOperations())) {
					HtmlOperationExample example = new HtmlOperationExample();
					example.or().andBizIdEqualTo(projectBiz.getId()).andTableNameEqualTo(tableName);
					projectTable.setHtmlOperations(htmlOperationMapper.selectByExample(example));
				}
				resultHtmlOperationList = projectTable.getHtmlOperations();
				for(HtmlOperation htmlOperation : resultHtmlOperationList){
					if(htmlOperation.getOpt() == null){
						returnHtmlOperationList.add(htmlOperation);
					}else{
						HtmlOperation returnHtmlOperation = JSONObject.toJavaObject(htmlOperation.getOpt(), HtmlOperation.class);
						returnHtmlOperationList.add(returnHtmlOperation);
					}
				}
				return returnHtmlOperationList;
			}
		}
		return null;
	}

	public void addHtmlOperationBean(List<HtmlOperation> itemReq, String tableName, Integer bizId) {
		Assert.notEmpty(itemReq, "表:" + tableName + "没有查询到字段");

		HtmlOperationExample example = new HtmlOperationExample();
		example.or().andBizIdEqualTo(bizId).andTableNameEqualTo(tableName);
		List<HtmlOperation> items = htmlOperationMapper.selectByExample(example);

		items = CollectionUtils.isEmpty(items) ? Lists.newArrayList() : items;
		for (int i = 0; i < itemReq.size(); i++) {	
			HtmlOperation ho = itemReq.get(i);
			ho.setBizId(bizId);
			ho.setTableName(tableName);
			ho.setOptContent(null);
			ho.setOptContent(JSON.toJSONString(ho));
			if (items.contains(ho)) {
				HtmlOperationExample example1 = new HtmlOperationExample();
				example1.or().andBizIdEqualTo(bizId).andTableNameEqualTo(tableName)
						.andColumnNameEqualTo(ho.getColumnName());
				htmlOperationMapper.updateByExampleSelective(ho, example1);
			} else {
				htmlOperationMapper.insertSelective(ho);
			}
		}
	}

	@Override
	public Set<String> getExistsTables(int bizId) {
		Set<String> temp = Sets.newHashSet();
		try {
			HtmlOperationExample example = new HtmlOperationExample();
			example.or().andBizIdEqualTo(bizId);

			List<HtmlOperation> db_list = htmlOperationMapper.selectByExample(example);
			if (db_list != null && db_list.size() > 0) {
				for (HtmlOperation htmlOperation : db_list) {
					if (htmlOperation.getTableName() != null) {
						temp.add(htmlOperation.getTableName());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	}

	@Override
	public List<DbInfo> selectLibrary(Integer id) {
		return dbInfoMapper.selectLibrary(id);
	}

	@Override
	public List<HtmlOperation> htmlopera(Integer id, String tableName) {
		HtmlOperation ho = new HtmlOperation();
		ho.setBizId(id);
		ho.setTableName(tableName);
		return htmlOperationMapper.htmlopera(ho);
	}


	@Override
	public List<HtmlOperation> tableHtml(String selectionLibrary) {
		// TODO Auto-generated method stub
		return htmlOperationMapper.tableHtml(selectionLibrary);
	}

	@Override
	public List<HtmlOperation> fieldHtml(String table) {
		// TODO Auto-generated method stub
		return htmlOperationMapper.fieldHtml(table);
	}



	


}
